// @ts-ignore
import {v4 as uuidv4} from 'uuid';
import {NButton} from "naive-ui";
import {renderIcon} from "@/utils";
import {resolveDirective, type VNode, withDirectives} from "vue";
import {format, parse} from "date-fns";

export function uuid(): string {
    return uuidv4();
}

export function copyToClipboard(text: string) {
    navigator.clipboard.writeText(text)
        .then(() => window.$message?.success('复制成功'))
        .catch(() => window.$message?.error('复制失败'));
}

export function clickCopyButton(text: string) {
    return h(NButton, {
        text: true,
        onClick: () => copyToClipboard(text)
    }, {default: renderIcon('lucide:copy', {size: 18})})
}

export function flattenTree(list: undefined | any[]): any[] {
    const result = []
    if (!list) {
        return result
    }

    function flatten(_list = []) {
        _list.forEach((item) => {
            result.push(item)
            flatten(item.children)
        })
    }

    flatten(list)
    return result
}

export function renderPermission(h: VNode, permissionCode: string) {
    return withDirectives(h, [[resolveDirective('p'), permissionCode]])
}

export function dateFormatByNumber(date: number, formatStr: string = 'yyyy-MM-dd HH:mm:ss') {
    return format(new Date(date), formatStr);
}

export function dateParse(date: string, formatStr: string = 'yyyy-MM-dd HH:mm:ss') {
    return parse(date, formatStr, new Date());
}

export function dateFormat(date: Date, formatStr: string = 'yyyy-MM-dd HH:mm:ss') {
    return format(date, formatStr);
}

export function localDateFormat(formatStr: string = 'yyyy-MM-dd HH:mm:ss') {
    return format(new Date(), formatStr);
}

export function get(condition: boolean, trueValue: any, falseValue: any) {
    return condition ? trueValue : falseValue
}

export function booleanToNumber(value: any): number | any {
    if (typeof value === 'boolean') {
        return value ? 1 : 0;
    }
    return value
}
